﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.ComponentModel.Composition;
using Steve.UI.Administration.Models;
using AutoMapper;

namespace Steve.UI.Administration.Controllers
{
    public class CategoryManagementControllerBase : Controller
    {
        [Import]
        public CategoryRepository Repository { get; set; }

        public virtual ActionResult CategoryList()
        {
            var categories = Repository.GetCategories();

            return View("CategoryList", categories);
        }

        public virtual ActionResult CategoryDetail(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                var model = new NewCategoryDetailModel();
                model.RelevancyWeight = 1;

                return View("NewCategoryDetail", model);
            }
            else
            {
                var model = new ExistingCategoryDetailModel();

                var category = Repository.GetCategory(id);

                Mapper.Map(category, (ExistingCategoryDetailModel)model);

                return View("ExistingCategoryDetail", model);
            }
        }

        [ActionName("CategoryDetail")]
        [HttpPost]
        [RouteValueAbsent("id")]
        public virtual ActionResult CategoryDetailPost(NewCategoryDetailModel model)
        {
            if (!ModelState.IsValid)
            {
                return View("NewCategoryDetail", model);
            }

            var category = new Category();

            Mapper.Map(model, category);

            Repository.SaveCategory(category);

            return RedirectToAction("CategoryList", "CategoryManagement");
        }

        [ActionName("CategoryDetail")]
        [HttpPost]
        [RouteValuePresent("id")]
        public virtual ActionResult CategoryDetailPost(ExistingCategoryDetailModel model, string id)
        {
            if (!ModelState.IsValid)
            {
                return View("ExistingCategoryDetail", model);
            }

            var category = new Category();

            Mapper.Map(model, category);

            category.CategoryName = id;

            Repository.SaveCategory(category);

            return RedirectToAction("CategoryList", "CategoryManagement");
        }
    }
}
